import random
import ConfigSpace as CS
import ConfigSpace.hyperparameters as CSH
import itertools

class Compress:
    cs_attributes = CS.ConfigurationSpace()
    attribute_list = ['axis']
    all_attributes = []

    def __init__(self):
        print('Compress Init--------------------------')
        self.init_all_attributes()
        self.init_cs()

    def init_all_attributes(self):
        for i in range(1, len(Compress.attribute_list)+1) :
            #此处取所有组合的可能值，存在列表里
            for attribute in itertools.combinations(Compress.attribute_list, i):
                l = list(attribute)
                Compress.all_attributes.append(l)

        #print('all_attributes: ', all_attributes)
        print('all attributes:')
        for a in Compress.all_attributes:
            print(a)

    def init_cs(self):
        length = len(Compress.all_attributes)
        attributes = CSH.UniformIntegerHyperparameter(name='combination', lower=0, upper=2*length)
        Compress.cs_attributes.add_hyperparameter(attributes)

    def get_random_combination(self):
        s = Compress.cs_attributes.sample_configuration()
        index = s.get_dictionary()['combination']
        print('get combination: ', index)

        length = len(Compress.all_attributes)

        #保证不带任何属性的case可以被覆盖到
        if index >= length:
            print('test no attributes')
            return []

        return Compress.all_attributes[index]       

    def get_max_attributes_combination(self):
        return len(Compress.all_attributes)

    def get_attributes_by_index_or_random(self, shapes, index):

        print('get_attributes_by_index_or_random, index: ', index)    
            
        attributes = {}
        shape_out = []

        print('Compress, shapes:', shapes[0])

        if index != -1:
            attr_combination = Compress.all_attributes[index]
        else:
            attr_combination = self.get_random_combination()

        if len(attr_combination) == 0:
            return attributes, shape_out    

        if 'axis' in attr_combination:
            #print('got axis, shapes[0]:', len(shapes[0]), shapes[0])
            axis = random.randint(-1*len(shapes[0]), len(shapes[0]) - 1)
            attributes['axis'] = axis

        print('------ attributes:', attributes, 'shape_out:', shape_out)

        return attributes, shape_out 

    def input_shape_correct(self, shapes):
        if len(shapes) != 2:
            return False

        max_dim = shapes[0][0]
        min_dim = shapes[0][0]

        for dim in shapes[0]:
            if dim > max_dim:
                max_dim = dim

            if dim < min_dim:
                min_dim = dim   

        shapes[1] = [random.randint(min_dim, max_dim)]

        return True            

    def get_input_type(self, name, type):
        if name == 'condition':
            return 'tensor(bool)'
        
        return type
            
